<template>
    <div>
        <a-form layout="inline"
                :model="searchData"
                style="margin: 10px 0">
            <a-form-item>
                <a-input v-model:value="searchData.name" placeholder="菜单名称"></a-input>
            </a-form-item>
            <a-form-item>
                <a-button type="primary" @click="load">搜索</a-button>
            </a-form-item>
            <a-form-item>
                <a-button type="default" @click="rest">重置</a-button>
            </a-form-item>
        </a-form>
        <a-button type="primary" style="margin-bottom: 10px" @click="openModal({})">新增</a-button>
        <a-table :dataSource="menuList"
                 :columns="columns"
                 :pagination="false"
                 :row-key="record => record.id"
                 :indentSize="70"
                 bordered>
            <template #type="{text,record}">
                {{text == 0 ? '不是' : '是'}}
            </template>
            <template v-slot:action="{text,record}">
                <a-button type="primary" @click="openModal(record)">编辑</a-button>
                <a-popconfirm
                        title="删除数据无法恢复，请确认是否删除？"
                        ok-text="是"
                        cancel-text="否"
                        @confirm="okDelete(record.id)"
                >
                    <a-button type="danger">删除</a-button>
                </a-popconfirm>
            </template>
        </a-table>
        <a-modal v-model:visible="visible" title="新增或编辑" @ok="handleOk">
            <a-form v-model="menu"
                    :label-col="{ span: 8 }">
                <a-form-item label="父级菜单" v-bind="validateInfos.parentId">
                    <a-cascader
                            v-model:value="menu.parentId"
                            :options="staticMenuList"
                            :field-names="{label: 'name',value: 'id',children: 'children'}"
                            placeholder="Please select"
                            change-on-select
                            @change="selectedHandle"
                    />
                </a-form-item>
                <a-form-item label="菜单名称" v-bind="validateInfos.name">
                    <a-input :disabled="menu.parentId == undefined" v-model:value="menu.name"></a-input>
                </a-form-item>
                <a-form-item label="路由路径">
                    <a-select :disabled="menu.parentId == undefined || menu.parentId == 0"
                              v-model:value="menu.url">
                        <a-select-option v-for="(item,i) in routerList" :value="item" :key="i">
                            {{item}}
                        </a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="排序" v-bind="validateInfos.sort">
                    <a-input :disabled="menu.parentId == undefined" v-model:value="menu.sort"></a-input>
                </a-form-item>
                <a-form-item label="公共资源">
                    <a-radio-group v-model:value="menu.common">
                        <a-radio :value="0">不是</a-radio>
                        <a-radio :value="1">是</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label="描述" v-bind="validateInfos.description">
                    <a-input :disabled="menu.parentId == undefined" v-model:value="menu.description"></a-input>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script>
    import {ref, onMounted} from 'vue'
    import {useRouter} from 'vue-router'
    import axios from 'axios'
    import {message, Form} from 'ant-design-vue';
    import {arrayToTree} from "../../util/Tool";
    export default {
        name: "system-menu",
        setup() {
            const columns = [
                {
                    title: '菜单名称',
                    dataIndex: 'name',
                    key: 'name',
                    width: '300px'
                },
                {
                    title: '公共资源',
                    dataIndex: 'type',
                    key: 'type',
                    align: 'center',
                    slots: {customRender: 'type'}
                },
                {
                    title: '路由路径',
                    dataIndex: 'url',
                    key: 'url',
                    align: 'center',
                    width: '200px'
                },
                {
                    title: '描述',
                    dataIndex: 'description',
                    key: 'description',
                    align: 'center',
                    width: '300px'
                },
                {
                    title: '操作',
                    key: 'action',
                    slots: {customRender: 'action'},
                    align: 'center',
                    width: '250px'
                }
            ]

            const router = useRouter()
            const useForm = Form.useForm
            const menu = ref({})
            const menuList = ref()
            const routerList = ref([])
            const staticMenuList = ref()
            const searchData = ref({})

            const {validate, validateInfos, resetFields} = useForm(menu, {
                parentId: [{required: true, message: '请选择父级权限', trigger: ['submit','change']}],
                name: [{required: true, message: '不能为空', trigger: ['submit','change']}]
            })

            const visible = ref(false);

            const load = () => {
                axios.get('/sys-resource/list', {
                    params: {
                        name: searchData.value.name,
                    }
                }).then(rs => {
                    console.log("查找结果：", rs)
                    let temp = arrayToTree(rs.data.data,0)

                    menuList.value = temp.length == 0 ? rs.data.data : temp

                })
            }

            const rest = () => {
                searchData.value = {}
                load()
            }

            const openModal = (obj) => {
                console.log("模态框参数：", obj)
                console.log("路由：", routerList.value)

                visible.value = true;
                menu.value = JSON.parse(JSON.stringify(obj))
                if (JSON.stringify(obj) == '{}') {
                    menu.value.name = ''
                    menu.value.parentId = undefined
                    resetFields()
                }
            }

            const handleOk = () => {
                validate().then(rs => {
                    // console.log("校验结果：", rs)
                    menu.value.parentId = menu.value.parentId[menu.value.parentId.length - 1]
                    axios.post('/sys-resource/saveOrUpdate', menu.value).then(rs => {
                        console.log("新增或修改结果：", rs)
                        if (rs.data.code == 200) {
                            visible.value = false
                            message.success("操作成功")
                            location.reload()
                            // load()
                        } else {
                            message.error(rs.data.message)
                        }
                    })
                }).catch(e => {
                    console.log("失败结果：", e)
                })
            }

            const okDelete = (id) => {
                console.log("要删除的ID：" + id)
                axios.delete('/sys-resource/delete/' + id).then(rs => {
                    if (rs.data.code == 200) {
                        message.success("删除成功")
                        load()
                    } else {
                        message.error(rs.data.message)
                    }
                })
            }

            const selectedHandle = (value, selectedOptions) =>{
                if (value.length >= 3){
                    message.warning("请勿超过3级菜单")
                    menu.value.parentId = null
                }
                // let tmp = value[value.length - 1]
                value.forEach(val=>{
                    if (val == menu.value.id){
                        message.warning("不能选择自身作为父级菜单")
                        menu.value.parentId = null
                    }
                })
            }

            onMounted(() => {
                axios.get('sys-resource/queryAll').then(rs=>{
                    staticMenuList.value = arrayToTree(rs.data.data,0)
                    menuList.value = arrayToTree(rs.data.data,0)
                    staticMenuList.value.unshift({
                        name: '父路径',
                        id: 0
                    })
                })
                router.options.routes.forEach(val=>{
                    if (val.name == 'home'){
                        val.children.forEach(value=>{
                            routerList.value.push(value.path)
                        })
                    }
                })
                // load()
            })
            return {
                columns,
                searchData,
                load,
                rest,
                openModal,
                visible,
                handleOk,
                okDelete,
                menu,
                menuList,
                validateInfos,
                staticMenuList,
                selectedHandle,
                routerList
            }
        }
    }
</script>

<style scoped>

</style>